package com.ruoyi.finance.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.finance.domain.*;
import com.ruoyi.finance.domain.DTO.KltPurchaseDetailStockDTO;
import com.ruoyi.finance.domain.DTO.KltSalesDetailStockDTO;
import com.ruoyi.finance.domain.VO.StockVO;
import com.ruoyi.finance.mapper.KltDeliverRecordDao;
import com.ruoyi.finance.mapper.KltStockDao;
import com.ruoyi.finance.service.KltPurchaseDetailService;
import com.ruoyi.finance.service.KltSalesDetailService;
import com.ruoyi.finance.service.KltStockService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * (KltStock)表服务实现类
 *
 * @author makejava
 * @since 2024-12-19 12:18:03
 */
@Service("kltStockService")
@Transactional
public class KltStockServiceImpl extends ServiceImpl<KltStockDao, KltStock> implements KltStockService {

    @Resource
    private KltStockDao kltStockDao;
    @Resource
    private KltSalesDetailService kltSalesDetailService;
    @Resource
    private KltPurchaseDetailService kltPurchaseDetailService;
    @Resource
    private KltDeliverRecordDao kltDeliverRecordDao;

    @Override
    public Integer getMaxId() {
        QueryWrapper<KltStock> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("stock_id").last("LIMIT 1");
        List<KltStock> kltStocks = kltStockDao.selectList(queryWrapper);
        if (kltStocks.isEmpty()) {
            return null; // 如果没有找到任何记录，则返回null或根据需要返回其他默认值
        }
        return kltStocks.get(0).getStockId();
    }

    @Override
    public List<KltStock> getAllKltPurchaseBatch(QueryWrapper<KltStock> kltStockQueryWrapper) {
        List<KltStock> kltPurchaseBatches = kltStockDao.selectList(kltStockQueryWrapper);
        return  kltPurchaseBatches;
    }


    @Override
    public List<StockVO> getStockByOrderIdAndDetail(Integer salesOrderid) {

//         根据订单找到所需订购的明细
        KltSalesDetail kltSalesDetail = new KltSalesDetail();
        kltSalesDetail.setSalesOrderId(String.valueOf(salesOrderid));
        List<KltSalesDetailStockDTO> allKltSalesDetailStockList = kltSalesDetailService.getAllKltPurchaseDetailStockList(kltSalesDetail);

        Map<String, KltSalesDetailStockDTO> resultMap = new HashMap<String, KltSalesDetailStockDTO>();
        for (KltSalesDetailStockDTO kltSalesDetailStockDTO : allKltSalesDetailStockList) {
            String key =kltSalesDetailStockDTO.getStockId();

            if (resultMap.containsKey(key)) {
                KltSalesDetailStockDTO value = new KltSalesDetailStockDTO();
                value.setSalesQuantity(resultMap.get(key).getSalesQuantity()+kltSalesDetailStockDTO.getSalesQuantity());
                resultMap.put(key,  value);
            } else {
                resultMap.put(key, kltSalesDetailStockDTO);
            }
        }

//        整理后根据订单id查找已经采购的明细
        KltPurchaseDetailStockDTO kltPurchaseDetailStockDTO = new KltPurchaseDetailStockDTO();
        kltPurchaseDetailStockDTO.setSalesOrderId(salesOrderid);
        List<KltPurchaseDetailStockDTO> allKltPurchaseDetailStockList = kltPurchaseDetailService.getAllKltPurchaseDetailStockList(kltPurchaseDetailStockDTO);
        Map<String, Integer> map1 = new HashMap<String, Integer>();
        Map<String, Integer> resultMap1 = new HashMap<String, Integer>();
        for (KltPurchaseDetailStockDTO kltPurchaseDetailStockDTO1 : allKltPurchaseDetailStockList) {

            String key = kltPurchaseDetailStockDTO1.getStockId();
            Integer value = kltPurchaseDetailStockDTO1.getQuantity();
            if (resultMap1.containsKey(key)) {
                resultMap1.put(key, resultMap1.get(key) + value);
            } else {
                resultMap1.put(key, value);
            }
        }

//        整合出所需采购的物品还有剩余数量
        List<StockVO> stockVOList = new ArrayList<>();
        for (Map.Entry<String, KltSalesDetailStockDTO> stringIntegerEntry : resultMap.entrySet()) {
            StockVO stockVO = new StockVO();
            stockVO.setStockId(String.valueOf(stringIntegerEntry.getKey()));
            if(resultMap1.entrySet().size()!=0){
                for (Map.Entry<String, Integer> integerEntry : resultMap1.entrySet()) {
                    if(Objects.equals(stringIntegerEntry.getKey(), integerEntry.getKey())){
                        stockVO.setOrderAmount(stringIntegerEntry.getValue().getSalesQuantity());
                        stockVO.setOrderPrice(stringIntegerEntry.getValue().getSalesUnitPrice());
                        stockVO.setInvoicingPrice(stringIntegerEntry.getValue().getSalesUnitPrice().divide(BigDecimal.valueOf(1.13),4, BigDecimal.ROUND_HALF_UP));
                        stockVO.setPurchaseAmount(integerEntry.getValue());
                    }
                    if(stockVO.getPurchaseAmount()==null){
                        stockVO.setOrderAmount(stringIntegerEntry.getValue().getSalesQuantity());
                        stockVO.setOrderPrice(stringIntegerEntry.getValue().getSalesUnitPrice());
                        stockVO.setInvoicingPrice(stringIntegerEntry.getValue().getSalesUnitPrice().divide(BigDecimal.valueOf(1.13),4, BigDecimal.ROUND_HALF_UP));

                        stockVO.setPurchaseAmount(0);
                    }
                }
            }else {
                stockVO.setPurchaseAmount(0);
                stockVO.setOrderPrice(stringIntegerEntry.getValue().getSalesUnitPrice());
                stockVO.setOrderAmount(stringIntegerEntry.getValue().getSalesQuantity());
                stockVO.setInvoicingPrice(stringIntegerEntry.getValue().getSalesUnitPrice().divide(BigDecimal.valueOf(1.13),4, BigDecimal.ROUND_HALF_UP));
            }
            for (KltSalesDetailStockDTO kltSalesDetailStockDTO : allKltSalesDetailStockList) {
                if(Objects.equals(kltSalesDetailStockDTO.getStockId(), stockVO.getStockId().toString())){
                    stockVO.setStockQuantity(kltSalesDetailStockDTO.getStockQuantity());
                    stockVO.setUnit(kltSalesDetailStockDTO.getUnit());
                    stockVO.setModel(kltSalesDetailStockDTO.getModel());
                    stockVO.setProductName(kltSalesDetailStockDTO.getProductName());
                }
            }
            stockVOList.add(stockVO);
        }
        return stockVOList;
    }

    public List<StockVO> getStockByOrderIdAndDetailArrive(Integer salesOrderid){
//        合同id => 明细 => 统计采购批次 => 合计采购数、到货数、库存数 加上已发货数 =>统计已发货数量
        List<StockVO> stockByOrderIdAndDetail = getStockByOrderIdAndDetail(salesOrderid);
        for (StockVO stockVO : stockByOrderIdAndDetail) {
            QueryWrapper<KltDeliverRecord> eq = new QueryWrapper<KltDeliverRecord>()
                    .eq("stock_id", stockVO.getStockId())
                    .eq("sales_order_id", salesOrderid)
                    .eq("is_del", "0")
                    ;
            eq.and(qr->qr.eq("deliver_type", "已发货").or().eq("deliver_type", "已完成"));

            List<KltDeliverRecord> kltDeliverRecords = kltDeliverRecordDao.selectList(eq);

            AtomicInteger amount = new AtomicInteger();
            kltDeliverRecords.forEach(kltDeliverRecord -> {
                amount.addAndGet(Math.toIntExact(kltDeliverRecord.getDeliverAmount()));
            });

            stockVO.setDeliverAmount(amount.get());
        }
        return stockByOrderIdAndDetail;
    }

    @Override
    public Boolean DeductInventoryShippingRecords(KltDeliverRecord kltDeliverRecord){

        // 扣除库存逻辑
        KltStock kltStock = kltStockDao.selectById(kltDeliverRecord.getStockId());
        if (kltStock == null || kltStock.getStockQuantity() < kltDeliverRecord.getDeliverAmount()) {
            return false; // 库存不足，扣减失败
        }
        kltStock.setStockQuantity(kltStock.getStockQuantity() - kltDeliverRecord.getDeliverAmount());
        kltStockDao.updateById(kltStock);


        // 生成发货记录
        kltDeliverRecord.setDeliverType("已发货");
        kltDeliverRecordDao.insert(kltDeliverRecord);

        return true;
    }


    @Override
    public Boolean UndeductInventoryShippingRecords(KltDeliverRecord kltDeliverRecord) {


        // 撤销扣除库存逻辑
        KltDeliverRecord kltDeliverRecord1 = kltDeliverRecordDao.selectById(kltDeliverRecord.getDeliverId());
        KltStock kltStock = kltStockDao.selectById(kltDeliverRecord1.getStockId());

        if (kltDeliverRecord1 == null) {
            return false; // 不存在
        }

        kltStock.setStockQuantity(kltStock.getStockQuantity() + kltDeliverRecord1.getDeliverAmount());
        kltStockDao.updateById(kltStock);


        // 生成发货记录
        kltDeliverRecord.setDeliverType("已退货");
        kltDeliverRecordDao.updateById(kltDeliverRecord);

        return true;
    }
}

